package com.todo.pro.jwt;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;

public class JwtUtil {
	/**
	 * 创建Token
	 * 
	 * @param claims
	 * @param ttlMillis
	 * @return
	 * @throws ExpiredJwtException
	 */
	public static String createToken(Map<String, Object> claims, long ttlMillis) {
		SecretKey key = generalKey();
		JwtBuilder jwtBuilder = Jwts.builder();
		long nowMillis = System.currentTimeMillis();
		Date now = new Date(nowMillis);
		long expMillis = nowMillis + ttlMillis;
		Date exp = new Date(expMillis);
		jwtBuilder.setClaims(claims).setIssuedAt(now).setExpiration(exp).signWith(key);
		return jwtBuilder.compact();
	}

	/***
	 * 解析Token
	 * 
	 * @param jwt
	 * @return
	 * @throws ExpiredJwtException
	 */
	public static Map<String, Object> parseJWT(String jwt) {
		SecretKey key = generalKey();
		JwtParser jwtParser = Jwts.parser().setSigningKey(key);
		try {
			return jwtParser.parseClaimsJws(jwt).getBody();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/***
	 * 由字符串生成加密key
	 * 
	 * @return
	 */
	private static SecretKey generalKey() {
		byte[] encodedKey = Base64.decodeBase64("9F8A92AAC52C48A39AAEF5D953384283201808311712");
		return new SecretKeySpec(encodedKey, 0, encodedKey.length, "HmacSHA256");
	}

	/***
	 * 测试
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		Map<String, Object> claims = new HashMap<>();
		claims.put("id", "XXXXXXXXXXXXXX");
		claims.put("userName", "NameXXX");
		String jwt = null;
		try {
			jwt = createToken(claims, 2000);
		} catch (Exception e) {
			e.printStackTrace();
		}

		System.out.println(jwt);

		try {
			claims = parseJWT(jwt);
			System.out.println(claims);
		} catch (ExpiredJwtException e) {
			System.out.println(e.getMessage());
			System.out.println(e.getLocalizedMessage());
			System.out.println(e.getHeader());
			System.out.println(e.getClaims());
		}

	}
}
